import { createRouter, createWebHistory } from 'vue-router'
import { getPaidOrders } from '@/utils/storage'

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/LoginView.vue')
    },
    {
        path: '/register',
        name: 'register',
        component: () => import('@/views/RegisterView.vue')
    },
    // 新增密码重置路由
    {
        path: '/reset-password',
        name: 'resetPassword',
        component: () => import('@/views/ResetPasswordView.vue')
    },
    {
        path: '/home',
        name: 'home',
        component: () => import('@/views/HomeView.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/restaurant/:id',
        name: 'restaurantDetail',
        component: () => import('@/views/RestaurantDetailView.vue'),
        props: true
    },
    {
        path: '/checkout',
        name: 'checkout',
        component: () => import('@/views/CheckoutView.vue'),
        props: (route) => ({
            orderItems: route.query.orderItems,
            totalAmount: route.query.totalAmount,
            restaurantId: route.query.restaurantId
        })
    },
    {
        path: '/alipay',
        name: 'alipay',
        component: () => import('@/views/AlipayView.vue'),
        props: (route) => ({ amount: route.query.amount })
    },
    {
        path: '/wechatpay',
        name: 'wechatpay',
        component: () => import('@/views/WechatPayView.vue'),
        props: (route) => ({ amount: route.query.amount })
    },
    {
        path: '/orders',
        name: 'orders',
        component: () => import('@/views/OrdersView.vue')
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

router.beforeEach((to, from, next) => {
    const isAuthenticated = localStorage.getItem('authToken')

    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!isAuthenticated) {
            next('/login')
        } else {
            next()
        }
    } else {
        next()
    }
})

export default router